﻿#include "accountdata.h"
#include "eventtype.h"
#include "debug.h"
#include <cassert>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonValue>

AccountData::AccountData()
	: QObject(0)
{
	m_base_infor = new AccountBaseInfor();
	m_net_infor = new AccountNetInfor();
}

AccountData::~AccountData()
{
}


AcountDataBuffer::AcountDataBuffer(QObject * p):QObject(p)
{
	m_group_ac_map = new GNmaeMapAcVec;
	m_Id_map = new IdMapAcData;
}

AcountDataBuffer::~AcountDataBuffer()
{

}

GNmaeMapAcVec * AcountDataBuffer::get_friend_map()
{
	return m_group_ac_map;
}

bool AcountDataBuffer::event(QEvent * e)
{
	auto type = e->type();

	if (type == UEvent::getFriendListEvent)
	{
		Debug("收到好友事件\n");
		
		FriendLsitEvent *fe = (FriendLsitEvent *)e;
		
		QJsonParseError jsonError;
		QJsonDocument doc = QJsonDocument::fromJson(QByteArray::fromStdString(fe->data_json),&jsonError);

		if (doc.isNull() && (jsonError.error != QJsonParseError::NoError))
		{
			Debug("解析错误\n");
			return QObject::event(e);
		}

		if (doc.isArray())
		{
			QJsonArray arr = doc.array();

			for (auto v:arr)
			{
				if (v.isObject())
				{
					QJsonObject g = v.toObject();
					QString gname = g.value("gname").toString();
					std::vector<AccountData *> vec;
					QJsonArray gunmber = g.value("gmunber").toArray();
					for (auto ac : gunmber)
					{
						QJsonObject a = ac.toObject();
						AccountData * d = new AccountData;
						d->m_base_infor = new AccountBaseInfor;
						d->m_net_infor = nullptr;
						auto p = d->m_base_infor;
						p->m_ac_number = a.value("id").toString();
						p->m_state = OffLine;
						p->m_name = a.value("name").toString();
						vec.push_back(d);
						m_Id_map->emplace(p->m_ac_number.toStdString(), d);
					}
					m_group_ac_map->emplace(gname.toStdString(), vec);
				}
			}


			emit dataRead();
		}
	}

	return QObject::event(e);
}
